package com.example.tsbs.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.tsbs.config.Response;
import com.example.tsbs.entity.Task;
import com.example.tsbs.service.TaskService;
import com.example.tsbs.util.FileUtil;
import com.example.tsbs.util.HttpRequest;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.Parameter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;

@Slf4j
@Api(tags="PyFileTest")
@RestController
@RequestMapping("/api")
public class PyFileTest {

    @Autowired
    private TaskService taskService;

    @ApiOperation("http调用测试")
    @PostMapping("/http")
    public String http() {
        String url = "http://127.0.0.1:3910/api/task/httpApi?id=1";
        String result = HttpRequest.getRequest(url);
        return result;
    }

    @ApiOperation("mysql读取和写入json数据")
    @PostMapping("/")
    public String mysqlTest() {
        Task task = taskService.getById(1);
        String parameter = task.getParameter();
        JSONObject json = JSON.parseObject(parameter);
        String model_path = json.getString("model_path");
        task.setResponse(null);
        taskService.updating(task, task.getId());
        return model_path;
    }

    @ApiOperation("模型Mesh类型py文件调用")
    @PostMapping("/pyMZMeshTest")
    public Response<?> pyMZMeshTest() {
        String pyFilePath = "/root/tsbsDuiJie/process_mesh_inp.py";
        String input_files = "{'/root/tsbsDuiJie/mesh20240401.inp'}";
        String json_path = "/root/tsbsDuiJie/part.json";

        String[] arguments = new String[] {"python3", pyFilePath, input_files, json_path };
        try {
            ProcessBuilder builder = new ProcessBuilder(arguments);
            Process p = builder.start();
            // 读取Python脚本的输出
            BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line = null;
            while ((line = in.readLine()) != null) {
                System.out.println(line);
            }
            in.close();
            // 等待Python脚本执行完成
            p.waitFor();
//            FileUtil.copy(new File(json_path),"/root");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return Response.success("success");
    }

    @ApiOperation("旧版频域py文件调用")
    @PostMapping("/pyOld")
    public Response<?> pyOld() {
        String pyFilePath = "/root/tsbs/gltf_interface.py";
        pyFilePath ="/root/tsbsDuiJie/ts/gltf_interface.py";

        int[] a = {0,120,20},b = {60,120,20};
        float c = 5000.0f;
        float[] model_coo_center = {0.0f,0.0f,0.0f};
        float[] model_coo_right = {0.0f,1.0f,0.0f};
        float[] model_coo_head = {1.0f,0.0f,0.0f};
        String name = "guapi.gltf";
        //转换成Python脚本对应参数 创建numpy数组的字符串表示，例如："np.array([1, 2, 3])"
        String hor = Arrays.toString(a);
        String ver = Arrays.toString(b);
        String freq = String.valueOf(c);
//        String center = "np.array("+ Arrays.toString(model_coo_center) +")";
//        String right = "np.array("+ Arrays.toString(model_coo_right) +")";
//        String head = "np.array("+ Arrays.toString(model_coo_head) +")";
        String center =  Arrays.toString(model_coo_center) ;
        String right =  Arrays.toString(model_coo_right) ;
        String head = Arrays.toString(model_coo_head) ;
        String nameStr = name;

        String[] arguments = new String[] {"python3", pyFilePath, hor, ver,freq, center,right,head,nameStr };
        try {
//            Process p = Runtime.getRuntime().exec(arguments);// 执行
            log.info("parameter参数："+ Arrays.toString(arguments));
            ProcessBuilder builder = new ProcessBuilder(arguments);
            Process p = builder.start();
            // 读取Python脚本的输出
            BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line = null;
            while ((line = in.readLine()) != null) {
                System.out.println(line);
            }
            in.close();
            // 等待Python脚本执行完成
            p.waitFor();
            FileUtil.copy(new File(name),"/root/tsbsDuiJie/gltf");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return Response.success("success");
    }

    @ApiOperation("新版频域py文件调用")
    @PostMapping("/pyBPTest")
    public Response<?> pyBPTest() {
        String pyFilePath = "/root/tsbs/gltf_interface.py";
        pyFilePath = "/root/tsbsDuiJie/ts/gltf_interface.py";

        int[] a = {0,120,20},b = {60,120,20};
        float c = 5000.0f;
        float[] model_coo_center = {0.0f,0.0f,0.0f};
        float[] model_coo_right = {0.0f,1.0f,0.0f};
        float[] model_coo_head = {1.0f,0.0f,0.0f};
        String name = "guapi.gltf";
        //转换成Python脚本对应参数 创建numpy数组的字符串表示，例如："np.array([1, 2, 3])"
        String hor = Arrays.toString(a);
        String ver = Arrays.toString(b);
        String freq = String.valueOf(c);
        String radius = "5000.0";
        String center =  Arrays.toString(model_coo_center) ;
        String right =  Arrays.toString(model_coo_right) ;
        String head = Arrays.toString(model_coo_head) ;
        String inp_path = "/root/tsbsDuiJie/time_light/mesh20240401.inp";
        String result_path = "/root";
        String nameLight = "light.gltf";
        String forToLight = "";

        String[] arguments = new String[] {"python3", pyFilePath, hor, ver,radius, center,right,head,name, inp_path, nameLight,forToLight };
        try {
//            Process p = Runtime.getRuntime().exec(arguments);// 执行
            ProcessBuilder builder = new ProcessBuilder(arguments);
            Process p = builder.start();
            // 读取Python脚本的输出
            BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line = null;
            while ((line = in.readLine()) != null) {
                System.out.println(line);
            }
            in.close();
            // 等待Python脚本执行完成
            p.waitFor();
            if (forToLight.equals("True")) {
                //for_light=True用于亮点计算（时域）
                FileUtil.copy(new File(nameLight), result_path);
            } else {
                //guapi.gltf用于瓜皮图（频域）
                FileUtil.copy(new File(name), result_path);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("Python脚本执行完成");
        return Response.success("success");
    }

    @ApiOperation("新版时域py文件调用")
    @PostMapping("/pyBSTest")
    public Response<?> pyBSTest() {
        String pyFilePath = "/root/tsbs/gltf_interface.py";
        pyFilePath = "/root/tsbsDuiJie/ts/gltf_interface.py";

        int[] a = {0,120,20},b = {60,120,20};
        float c = 5000.0f;
        float[] model_coo_center = {0.0f,0.0f,0.0f};
        float[] model_coo_right = {0.0f,1.0f,0.0f};
        float[] model_coo_head = {1.0f,0.0f,0.0f};
        String name = "guapi.gltf";
        //转换成Python脚本对应参数 创建numpy数组的字符串表示，例如："np.array([1, 2, 3])"
        String hor = Arrays.toString(a);
        String ver = Arrays.toString(b);
        String freq = String.valueOf(c);
        String radius = "5000.0";
        String center =  Arrays.toString(model_coo_center) ;
        String right =  Arrays.toString(model_coo_right) ;
        String head = Arrays.toString(model_coo_head) ;
        String inp_path = "/root/tsbsDuiJie/time_light/mesh20240401.inp";
        String result_path = "/root";
        String nameLight = "light.gltf";
        String forToLight = "True";

        String[] arguments = new String[] {"python3", pyFilePath, hor, ver,radius, center,right,head,name, inp_path, nameLight,forToLight };
        try {
//            Process p = Runtime.getRuntime().exec(arguments);// 执行
            ProcessBuilder builder = new ProcessBuilder(arguments);
            Process p = builder.start();
            // 读取Python脚本的输出
            BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line = null;
            while ((line = in.readLine()) != null) {
                System.out.println(line);
            }
            in.close();
            // 等待Python脚本执行完成
            p.waitFor();
            if (forToLight.equals("True")) {
                //for_light=True用于亮点计算（时域）
                FileUtil.copy(new File(nameLight), result_path);
            } else {
                //guapi.gltf用于瓜皮图（频域）
                FileUtil.copy(new File(name), result_path);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("Python脚本执行完成");
        return Response.success("success");
    }


    @ApiOperation("直接调用py文件")
    @PostMapping("/pyFile")
    public Response<?> pyFileTest() {
        String res = "";
        String pyFilePath = "/root/tsbs/gltf_interface.py";
        pyFilePath ="/root/tsbsDuiJie/gltf_interface.py";
        if(!FileUtil.isFileExist(pyFilePath)) {
            return Response.success("py不存在");
        }

        try {
            // Command to execute the Python script
            String[] command = {"python3", pyFilePath};
            // Create the process builder
            ProcessBuilder pb = new ProcessBuilder(command);
            // Start the process
            Process process = pb.start();
            // Read output from the Python script
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            // Wait for the process to finish
            int exitCode = process.waitFor();
            System.out.println("Python script exited with code: " + exitCode);

        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }

        return Response.success(res);
    }
}
